package cn.edu.sdyu.ie.crs.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Map;

@Slf4j
@Component
public class RestHttpClient {

    @Autowired
    private RestTemplate restTemplate;

    @Bean("restTemplate")
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

    public String executeByGet(String url, String token) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);
        headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        HttpEntity entity = new HttpEntity(headers);

        log.info(url);

        String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
        return result;
    }

    public String executeByPost(String url, String token, String entityId) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);
        headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        Map<String, Object> requestParam = Map.of("entity_id", entityId);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<Map<String, Object>>(requestParam, headers);

        log.info(url);
        String result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
        return result;
    }
}
